<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-upload
              :http-request="uploadFile"
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="3"
              :on-exceed="handleExceed"
              :file-list="fileList">
            <el-button size="big" type="success" icon="el-icon-upload">导入文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="exportData" type="success" icon="el-icon-download"> 导出文件</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.data" highlight-current-row :v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="nickname" label="称呼" width="120" sortable>
      </el-table-column>
      <el-table-column prop="company" label="公司" width="120" sortable>
      </el-table-column>
      <el-table-column prop="career" label="职业" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="120" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120" sortable>
      </el-table-column>
      <el-table-column prop="mobilephone" label="移动电话" width="120" sortable>
      </el-table-column>
      <el-table-column prop="address" label="地址" width="120" sortable>
      </el-table-column>
      <el-table-column prop="desc" label="介绍" width="120" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize"
                     :total="pageInfo.total"
                     style="float:right;">
      </el-pagination>
    </el-col>


    <!--新增和编辑界面-->
    <el-dialog title="新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="称呼" prop="nickname">
          <el-input v-model="saveForm.nickname" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="公司" prop="company">
          <el-input v-model="saveForm.company" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="职业" prop="career">
          <el-input v-model="saveForm.career" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="移动手机" prop="mobilephone">
          <el-input v-model="saveForm.mobilephone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="saveForm.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="desc">
          <el-input v-model="saveForm.desc" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      pageInfo: {
        total: 0, // 总的数据条数
        data: [] // 列表数据
      }, // 分页数据
      query: {  // 查询分页
        currentPage: 1, // 当前页码
        pageSize: 10, // 查询条数
        keyword: '' // 关键字
      },
      departments: [],// 部门列表
      clueTree: [],// 多级部门树
      page: 1,
      listLoading: false, // 列表加载
      sels: [],//列表选中列
      saveFormVisible: false,//编辑新增界面是否显示
      saveLoading: false, // 编辑新增弹出框提交加载
      saveFormRules: {  //  编辑新增规则
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      saveForm: {}, //新增编辑界面数据
      fileList: [],// 上传文件数组
    }

  },
  methods: {
    // 导出
    exportData() {
      axios.post("/clue/exportExcel").then(res => {
        if (res.status == 200) {
          // 导出成功
          this.$message.success("导出成功")
        }
      }).catch(() => {
        this.$message.error("导出失败")
      })

    },
    uploadFile(file) {
      let formData = new FormData()
      formData.append("file", file.file)
      axios.post("/clue/importExcel", formData).then(res => {
        if (res.status == 200) {
          // 导入成功
          this.$message.success("导入成功")
        }
      }).catch(() => {
        this.$message.error("导入失败")
      })
    },

    handleRemove(file, fileList) {
      // console.log("handleRemove", file, fileList);
    },
    // 上传
    handlePreview(file) {
      // console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 获取
    getParents() {
      axios.get("/clue").then(res => {
        if (res.status == 200) {
          // 查询成功
          this.departments = res.data.data
        }
      })
    },
    // 获取部门树方法
    getDeptTree() {
      axios.get("/clue/parent").then(res => {
        if (res.status == 200) {
          // 查询成功
          this.clueTree = res.data.data;
        }
      })
    },
    // 状态切换
    formatState() {
      return this.pageInfo.data.state == 0 ? "正常" : "停用";
    },
    // 分页查询携带数据
    search() {
      this.query.currentPage = 1;
      this.getClue();
    },
    // 监听当前是第几页，查询第几条数据
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getClue();
    },
    //获取用户列表
    getClue() {
      axios.put("/clue", this.query).then(res => {
        if (res.status == 200) {
          // 查询成功
          this.$message.success("分页查询成功")
          this.pageInfo = res.data.data
        }
      }).catch(() => {
        this.$message.error("分页查询失败")
      })
    },
    //删除
    handleDel(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let id = row.id;
        // 删除方法
        console.log(typeof id)
        this.deleteById(id)
      }).catch(() => {

      });
    },
    // 删除方法
    deleteById(id) {
      axios.delete("/clue/" + id).then(res => {
        if (res.status == 200) {
          // 关闭加载框
          this.listLoading = false;
          // 删除成功
          this.$message.success("删除成功")
        }
      }).catch(() => {
        // 删除失败
        this.$message.error("删除失败")
      }).finally(() => {
        this.getClue()
      })
    },
    //显示编辑界面
    handleEdit(index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      // 上级部门树回显

      this.getParents()
      this.getDeptTree()
    },
    //显示新增界面
    handleAdd() {
      this.saveFormVisible = true;
      this.saveForm = {};
      this.getParents()
      this.getDeptTree()
    },
    //新增编辑
    saveSubmit() {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            // 提交新增编辑方法
            this.insertOrUpdate();
          });
        }
      });
    },
    // 新增修改
    insertOrUpdate() {
      console.log(this.saveForm)
      console.log(this.saveForm.parent)

      if (this.saveForm.parent) {
        this.saveForm.parent = {
          id: this.saveForm.parent[this.saveForm.parent.length - 1]
        }
      } else {
        this.saveForm.parent = {
          id: null
        }
      }


      if (this.saveForm.parent) {
        // 转为对象
        this.saveForm.parent = {...this.saveForm.parent}
      }

      axios.post("/clue", this.saveForm).then(res => {
        // 成功信息
        if (res.status == 200) {
          this.$message.success("保存成功")
        }
        // 关闭加载框
        this.saveLoading = false;
        // 关闭弹框
        this.saveFormVisible = false
      }).catch(() => {
        this.$message.error("保存失败")
      }).finally(() => {
        this.getClue()
      })
    },
    // 列表选中列的变化
    selsChange(sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove() {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // 批量删除
        this.batchDelete(ids);
      }).catch(() => {

      });
    },
    // 批量删除方法
    batchDelete(ids) {
      axios.patch("/clue", ids)
          .then(res => {
            if (res.status == 200) {
              // 批量删除成功
              this.$message.success("批量删除成功")
              // 关闭弹框
              this.listLoading = false;
              this.query.currentPage = 1
            }
          })
          .catch(() => {
            this.$message.error("批量删除失败")
          })
          .finally(() => {
            this.getClue()
          })
    }
  },
  mounted() {
    this.getClue();
  }
}

</script>

<style scoped>

.upload-demo {

}

</style>